package com.lb;

import redis.clients.jedis.DefaultJedisClientConfig;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisClientConfig;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.params.SetParams;

import java.util.HashSet;
import java.util.Set;



/**
 * Hello world!
 *
 */
public class App 
{
    private static JedisCluster jedisCluster;

    // 初始化 Redis Cluster 连接
    static {
        Set<HostAndPort> clusterNodes = new HashSet<>();
        clusterNodes.add(new HostAndPort("47.120.36.156", 30001));
        clusterNodes.add(new HostAndPort("47.120.36.156", 30002));
        clusterNodes.add(new HostAndPort("47.120.36.156", 30003));
        clusterNodes.add(new HostAndPort("47.120.36.156", 30004));
        clusterNodes.add(new HostAndPort("47.120.36.156", 30005));
        clusterNodes.add(new HostAndPort("47.120.36.156", 30006));

        // JedisCluster 会自动发现集群拓扑（主从、分片）
        // jedisCluster = new JedisCluster(clusterNodes);
        JedisClientConfig clientConfig = DefaultJedisClientConfig.builder()
                .password("yourpassword")           // ← 替换为你的真实密码
                .connectionTimeoutMillis(2000
                )
                .socketTimeoutMillis(2000
                )
                .build();

        // 3. 创建 JedisCluster 实例
        jedisCluster = new
                JedisCluster(clusterNodes, clientConfig);
    }
    public static void main(String[] args) throws InterruptedException {
        // 启动多个线程模拟并发
        Thread t1 = new Thread(() -> {
            try {
                executeWithLock("client_01");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });

        Thread t2 = new Thread(() -> {
            try {
                executeWithLock("client_02");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });

        t1.start();
        t2.start();

        t1.join();
        t2.join();

        try {
            jedisCluster.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void executeWithLock(String clientId) throws InterruptedException {
        String lockKey = "my:lock";

        try {
            System.out.println("[" + clientId + "] 正在尝试获取锁...");

            String result = jedisCluster.set(lockKey, clientId,
                    SetParams.setParams().nx().ex(1000)); // NX=不存在才设，EX=10秒过期

            if ("OK".equals(result)) {

                System.out.println("✅ [" + clientId + "] 成功获取锁！开始执行业务...");
                Thread.sleep(500000); // 模拟耗时操作
                System.out.println("✅ [" + clientId + "] 业务执行完成。");
            } else {
                System.out.println("❌ [" + clientId + "] 获取锁失败，锁已被占用。");
            }
        } catch (Exception e) {
            System.out.println("❌ [" + clientId + "] 执行出错: " + e.getMessage());
        } finally {
            // 注意：这里不能随便删！生产环境要判断是不是自己持有的锁
            String currentOwner = jedisCluster.get(lockKey);
            if (currentOwner != null && currentOwner.equals(clientId)) {
                Thread.sleep(10000);
                jedisCluster.del(lockKey);
                System.out.println("🔓 [" + clientId + "] 释放了自己的锁。");
            } else {
                System.out.println("⚠️  [" + clientId + "] 没有持有锁，跳过释放。");
            }
        }
    }
}
